package com.brett.frame.learn.util;

import java.util.ArrayDeque;
import java.util.Random;

import lombok.Data;

public class TreeBuilder {

	DataBuilder builder = new DataBuilder();
	private static final Random r = new Random(System.currentTimeMillis());
	private Integer max = Integer.MAX_VALUE;

	public Integer getMax() {
		return max;
	}

	public TreeBuilder setMax(Integer max) {
		this.max = max;
		return this;
	}

	public TreeNode createNode() {
		return new TreeNode(TreeBuilder.r.nextInt(getMax()));
	}

	public TreeNode createNode(int data) {
		return new TreeNode(data);
	}

	@Data
	public static class TreeNode {
		int data;
		TreeNode leftNode;
		TreeNode rightNode;

		public TreeNode(int data) {
			this.data = data;
		}
	}

 

	public void print(TreeNode root) {
		System.out.println("打印树：");
		ArrayDeque<TreeNode> queue = new ArrayDeque<>();
		queue.offerFirst(root);
		int row = 1;
		int col = 0;
		TreeNode tmp;
		while ((tmp = queue.pollLast()) != null) {
			if (tmp.getLeftNode() != null) {
				queue.offerFirst(tmp.getLeftNode());
				col++;
			}
			if (tmp.getRightNode() != null) {
				queue.offerFirst(tmp.getRightNode());
				col++;
			}
			System.out.print(tmp.getData() + " ");
			row--;
			if (row == 0) {
				System.out.println("");
				row = col;
				col = 0;
			}
		}
	}

	public void print(TreeNode root, int size) {
		TreeNode[] arr = new TreeNode[size];
		this.toArr(arr, root, 0);
		for (int i = 0; i < arr.length; i++) {
			System.out.print(String.format("i%d=%d, ", i, arr[i].getData()));
		}
	}

	public void toArr(TreeNode[] arr, TreeNode node, int i) {
		if (node == null)
			return;
		arr[i] = node;
		if (2 * i + 1 < arr.length ) {
			toArr(arr, node.leftNode, 2 * i + 1);
		}
		if (2 * i + 2 < arr.length) {
			toArr(arr, node.rightNode, 2 * i + 2);
		}
	}
}
